<template>
  <view>
    <uni-search-bar @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    
    <!-- 搜索建议列表 -->
    <!-- <view class="sugg-list">
      <view class="sugg-item">
        <view class="goods-name"></view>
        <uni-icons type=""></uni-icons>
      </view>
    </view> -->
    <uni-list v-if="searchResults.length > 0">
      <uni-list-item showArrow :title="item.goods_name" v-for="(item,index) in searchResults" :key="index" @click="gotoGoodsList(item)"></uni-list-item>
    </uni-list>
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" @click="clearSearchHistory"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag v-for="(item,index) in historyList" :key="index" :text="item" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer:null,
        //搜索结果
        searchResults:[],
        // 搜索记录
        historyList:uni.getStorageSync('keyword')?JSON.parse(uni.getStorageSync('keyword')):[]
      };
    },
    methods:{
      //防抖
      input(e){
        if(this.timer){
          clearTimeout(this.timer)
          // this.timer = null
        }
        this.timer = setTimeout(()=>{
          //  点击清空 ，不发请求
          if(!e) return this.searchResults = []
          this.getSearchList(e)
          this.saveSearchHistory(e)
        },500)
      },
      //获取搜索建议
      async getSearchList(query){

        // 发送请求
        let {data:res}= await uni.$http.get('/goods/qsearch',{query})
        if(res.meta.status !==200) return uni.$showMsg()
        this.searchResults = res.message
      },
      saveSearchHistory(query){
        let set = new Set(this.historyList)
        set.add(query)
        this.historyList = [...set]   
        // 持久化数据
        console.log()
        uni.setStorageSync('keyword',JSON.stringify(this.historyList))
      },
      // 删除历史记录
      clearSearchHistory(){
        this.historyList = []
        uni.setStorageSync('keyword','[]')
      },
      // 跳转页面
      gotoGoodsList(query){
        uni.navigateTo({
          url:"/subpkg/goods_list/goods_list?query="+query
        })
      }
    }
  }
</script>

<style lang="scss">
.history-box{
  padding: 0 5px;
  .history-title{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }
  .uni-tag{
    margin-top: 5px;
    margin-right: 5px;
  }
}
</style>
